package sort;

import java.util.Arrays;

public class MergeSort {
    public static void main(String[] args) {
        int[] arr = {4,2,7,9,8,6,3,-5,-10,100};

        //long startTime = System.currentTimeMillis();
        //int[] arr = new int[80000];
        int[] temp = new int[arr.length];
        //initArr(arr);
        mergeSort(arr,0,arr.length-1,temp);
        //long endTime = System.currentTimeMillis();
       // System.out.println("程序运行时间：" + (endTime - startTime) + "ms");
        System.out.println(Arrays.toString(arr));
    }

    static void initArr(int[] arr) {

        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) (Math.random() * 8000000);
        }
    }
    public static void mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            int mid = left + (right - left) / 2;
            mergeSort(arr, left, mid, temp);
            mergeSort(arr, mid + 1, right, temp);
            merge(arr, left, mid, right, temp);
        }
    }

    public static void merge(int[] arr, int left, int mid, int right, int[] tmp) {
        int i = left;
        int j = mid + 1;
        int t = 0;
        while (i <= mid && j <= right) {
            if (arr[i] <= arr[j]) {
                tmp[t++] = arr[i++];
            } else {
                tmp[t++] = arr[j++];
            }
        }
        while (i <= mid) {
            tmp[t++] = arr[i++];
        }
        while (j <= right) {
            tmp[t++] = arr[j++];
        }
        t = 0;
        while (left <= right) {
            arr[left++] = tmp[t++];
        }
    }
}
